import React, { useState } from "react";
import { Row, Col, Button, message, PageHeader, Spin } from "antd";
import BraftEditor from "braft-editor";
import "braft-editor/dist/index.css";

import { _updateUserIntro } from "../../util/api/user/index";

class AddArticle extends React.Component {
  constructor(props){
    super(props)
    this.state = {
      editorState: BraftEditor.createEditorState(null),
      user_id: null,
      isshow: false,
      isLoading: false,
    };
  }
  

  async componentDidMount() {
    // 假设此处从服务端获取html格式的编辑器内容
    let d_user = await JSON.parse(localStorage.getItem("d_user"))
    const htmlContent = d_user.user_introduce;
    // 使用BraftEditor.createEditorState将html字符串转换为编辑器需要的editorStat
    this.setState({
      editorState: BraftEditor.createEditorState(htmlContent),
    });
  }

  submitContent = async () => {
    // 在编辑器获得焦点时按下ctrl+s会执行此方法
    // 编辑器内容提交到服务端之前，可直接调用editorState.toHTML()来获取HTML格式的内容
    // const rawString = this.state.editorState.toRAW();
    // 引入编辑器组件
    this.setState({ isLoading: true });
    let c_user = JSON.parse(localStorage.getItem("c_user"));
    let user_id = c_user.user_id;
    const htmlString = this.state.editorState.toHTML();

    let tempData = {
      user_introduce: htmlString,
    };
    _updateUserIntro(user_id, tempData)
      .then((res) => {
        if (res.status === 200 && res.data.code === 0) {
          
          localStorage.setItem("d_user", JSON.stringify(tempData));
          this.setState({ isLoading: false });
          message.success("更新成功",1.5).then(() =>{
            window.history.back()
          });
        }
      })
      .catch(() => {
        this.setState({ isLoading: false });
        message.error("服务器错误");
      });
  };

  handleEditorChange = (editorState) => {
    this.setState({ editorState });
  };
  // 预览
  preview = () => {
    if (window.previewWindow) {
      window.previewWindow.close();
    }

    window.previewWindow = window.open();
    window.previewWindow.document.write(this.buildPreviewHtml());
    window.previewWindow.document.close();
  };
  buildPreviewHtml() {
    return `
      <!Doctype html>
      <html>
        <head>
          <title>Preview Content</title>
          <style>
            html,body{
              height: 100%;
              margin: 0;
              padding: 0;
              overflow: auto;
              background-color: #f1f2f3;
            }
            .container{
              box-sizing: border-box;
              width: 1000px;
              max-width: 100%;
              min-height: 100%;
              margin: 0 auto;
              padding: 30px 20px;
              overflow: hidden;
              background-color: #fff;
              border-right: solid 1px #eee;
              border-left: solid 1px #eee;
            }
            .container img,
            .container audio,
            .container video{
              max-width: 100%;
              height: auto;
            }
            .container p{
              white-space: pre-wrap;
              min-height: 1em;
            }
            .container pre{
              padding: 15px;
              background-color: #f1f1f1;
              border-radius: 5px;
            }
            .container blockquote{
              margin: 0;
              padding: 15px;
              background-color: #f1f1f1;
              border-left: 3px solid #d1d1d1;
            }
          </style>
        </head>
        <body>
          <div class="container">${this.state.editorState.toHTML()}</div>
        </body>
      </html>
    `;
  }
  render() {
    const { editorState } = this.state;
    const excludeControls = ["media", "emoji"];
    const extendControls = [
      {
        key: "custom-button",
        type: "component",
        component: (
          <button
            type="button"
            className="control-item button upload-button"
            data-title="预览"
            onClick={this.preview}
          >
            预览
          </button>
        ),
      },
    ];
    return (
      <div style={{ minHeight: 360 }}>
        <Row>
          {/* <Col span={4}>
        <Button type="primary" block>
          保存修改
        </Button>
      </Col> */}
          <Col span={24}>
            <PageHeader
              ghost={false}
              onBack={() => window.history.back()}
              subTitle="个人主页设置"
              extra={[
                <Button type="primary" block onClick={this.submitContent}>
                  保存修改
                </Button>,
              ]}
            ></PageHeader>
          </Col>
        </Row>
        <br />
        <Row>
          <Col span={24}>
            <Spin tip="Loading..." spinning={this.state.isLoading}>
              <BraftEditor
                value={editorState}
                onChange={this.handleEditorChange}
                onSave={this.submitContent}
                extendControls={extendControls}
                excludeControls={excludeControls}
              />
            </Spin>
          </Col>
        </Row>
      </div>
    );
  }
}

export default AddArticle;
